package whu.cachhe.makeorder.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import whu.cachhe.makeorder.R;
import whu.cachhe.makeorder.domain.Reservation;
import whu.cachhe.makeorder.net.HttpRequest;
import whu.cachhe.makeorder.net.URLConstant;
import whu.cachhe.makeorder.util.Logger;
import whu.cachhe.makeorder.view.WrapContentListView;

/**
 * Created by CocoAdapter on 2018/4/2.
 */

public class MyReservationsActivity extends AppCompatActivity {
    private WrapContentListView listViewCurr;
    private WrapContentListView listViewHistory;

    private List<Reservation> currList;
    private List<Reservation> historyList;

    private CurrAdapter currAdapter;
    private HistoryAdapter historyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_reservations);

        init();

        getReservationRecords(MainActivity.user.getReserveSysId());
    }

    private void init(){
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("我的预约");

        listViewCurr = findViewById(R.id.list_view_curr);
        listViewHistory = findViewById(R.id.list_view_history);

        currList = new ArrayList<>();
        currAdapter = new CurrAdapter(this, currList);
        listViewCurr.setAdapter(currAdapter);
        historyList = new ArrayList<>();
        historyAdapter = new HistoryAdapter(this, historyList);
        listViewHistory.setAdapter(historyAdapter);

        setListener();
    }

    private void setListener(){
        View.OnClickListener ocl = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.img_back:
                        finish();
                        break;

                }
            }
        };

        ImageView imgBack = findViewById(R.id.img_back);
        imgBack.setOnClickListener(ocl);

    }

    private void getReservationRecords(String uid){
        if (currList == null)
            currList = new ArrayList<>();
        if (historyList == null)
            historyList = new ArrayList<>();

        if (currAdapter == null)
            currAdapter = new CurrAdapter(MyReservationsActivity.this, currList);

        if (historyAdapter == null)
            historyAdapter = new HistoryAdapter(MyReservationsActivity.this, historyList);

        try {
            JSONObject fparam = new JSONObject()
                    .put("uid", uid);

            HttpRequest.post(URLConstant.HOST, "getAppsByUsrId", fparam, new HttpRequest.HttpRequestCallback() {
                @Override
                public void onSuccess(JSONObject response) {
                    if (response.optInt("success") == 1){
                        currList.clear();
                        historyList.clear();

                        JSONArray data = response.optJSONObject("result").optJSONArray("data");
                        if (data != null){
                            int length = data.length();
                            for(int i = 0; i < length; i++) {
                                JSONObject jR = data.optJSONObject(i);
                                Reservation r = new Reservation();
                                r.setId(jR.optString("appid"));
                                r.setStartTime(jR.optString("startTime"));
                                r.setEndTime(jR.optString("endTime"));
                                r.setLotId(jR.optString("lotId"));
                                r.setStatus(jR.optInt("status"));
                                r.setLotName(jR.optString("lotName"));
                                r.setParkingName(jR.optString("parkName"));
                                r.setPid(jR.optString("pid"));
                                r.setInfo(jR.optString("info"));
                                r.setIfObey(jR.optInt("ifobey"));
                                r.setActualBeginTime(jR.optString("actualBeginTime"));
                                r.setActualEndTime("actualEndTime");
                                if (r.getStatus() == 0 || r.getStatus() == -3)
                                    currList.add(r);

                                else
                                    historyList.add(r);
                            }
                        }

                        currAdapter.notifyDataSetChanged();
                        historyAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(MyReservationsActivity.this, response.optString("result"), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure() {
                    Toast.makeText(MyReservationsActivity.this, "网络异常", Toast.LENGTH_LONG).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void cancelReserve(String uid, final String appid){
        try {
            JSONObject fparam = new JSONObject()
                    .put("uid", uid)
                    .put("appid", appid);

            HttpRequest.post(URLConstant.HOST, "cancelAppointment", fparam, new HttpRequest.HttpRequestCallback() {
                @Override
                public void onSuccess(JSONObject response) {
                    if (response.optInt("success") == 1){
                        Toast.makeText(MyReservationsActivity.this,
                                response.optJSONObject("result").optString("msg"), Toast.LENGTH_LONG).show();

                        for (int i = 0; i < currList.size(); i++){
                            if (currList.get(i).getId().equals(appid)){
                                Reservation r = currList.remove(i);
                                r.setStatus(-1);
                                historyList.add(r);
                                currAdapter.notifyDataSetChanged();
                                historyAdapter.notifyDataSetChanged();
                                return;
                            }
                        }
                    } else {
                        Toast.makeText(MyReservationsActivity.this, response.optString("result"), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure() {
                    Toast.makeText(MyReservationsActivity.this, "网络异常", Toast.LENGTH_LONG).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    // TODO 直接刷新所有，没有局部刷新
    private void finishReserve(String uid, final String lotId){
        try {
            JSONObject fparam = new JSONObject()
                    .put("uid", uid)
                    .put("lotId", lotId);

            HttpRequest.post(URLConstant.HOST, "updateAppStatus", fparam, new HttpRequest.HttpRequestCallback() {
                @Override
                public void onSuccess(JSONObject response) {
                    if (response.optInt("success") == 1){
                        Toast.makeText(MyReservationsActivity.this,
                                response.optJSONObject("result").optString("msg"), Toast.LENGTH_LONG).show();

                        for (int i = 0; i < currList.size(); i++){
                            if (currList.get(i).getLotId().equals(lotId)){
                                Reservation r = currList.remove(i);
                                r.setStatus(-2);
                                historyList.add(r);
                                currAdapter.notifyDataSetChanged();
                                historyAdapter.notifyDataSetChanged();
                                return;
                            }
                        }
                    } else {
                        Toast.makeText(MyReservationsActivity.this, response.optString("result"), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure() {
                    Toast.makeText(MyReservationsActivity.this, "网络异常", Toast.LENGTH_LONG).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private class HistoryAdapter extends BaseAdapter {
        private List<Reservation> reservationList;
        private Context context;

        public HistoryAdapter(Context context, List<Reservation> reservationList){
            this.context = context;
            this.reservationList = reservationList;
        }

        @Override
        public int getCount() {
            return reservationList.size();
        }

        @Override
        public Object getItem(int position) {
            return reservationList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HistoryViewHolder holder;
            if (convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_my_reservations_history, null);
                holder = new HistoryViewHolder();
                holder.time = convertView.findViewById(R.id.tv_time);
                holder.location = convertView.findViewById(R.id.tv_location);
                holder.status = convertView.findViewById(R.id.tv_status);
                holder.reason = convertView.findViewById(R.id.tv_reason);
                holder.operation = convertView.findViewById(R.id.ll_end);

                convertView.setTag(holder);
            } else
                holder = (HistoryViewHolder) convertView.getTag();
            // update holder
            final Reservation r = reservationList.get(position);
            holder.time.setText(r.getStartTime() + "至" + r.getEndTime());
            holder.location.setText(r.getParkingName() + " " + r.getLotName());
            switch (r.getStatus()){
                case -2:
                    holder.status.setText("已履约");
                    holder.reason.setVisibility(View.GONE);
                    holder.operation.setOnClickListener(null);
                    break;
                case -1:
                    holder.status.setText("已取消");
                    holder.reason.setVisibility(View.GONE);
                    holder.operation.setOnClickListener(null);
                    break;
            }
            if (r.getIfObey() == 1){
                holder.status.setText("违规");
                holder.reason.setVisibility(View.VISIBLE);
                holder.operation.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new android.app.AlertDialog.Builder(context)
                                .setTitle("违规原因")
                                .setMessage(r.getInfo())
                                .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                    }
                });
            }
            return convertView;
        }
    }

    private class CurrAdapter extends BaseAdapter {
        private List<Reservation> reservationList;
        private Context context;

        public CurrAdapter(Context context, List<Reservation> reservationList){
            this.context = context;
            this.reservationList = reservationList;
        }

        @Override
        public int getCount() {
            return reservationList.size();
        }

        @Override
        public Object getItem(int position) {
            return reservationList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CurrViewHolder holder;
            if (convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_my_reservations_curr, null);
                holder = new CurrViewHolder();
                holder.time = convertView.findViewById(R.id.tv_time);
                holder.location = convertView.findViewById(R.id.tv_location);
                holder.status = convertView.findViewById(R.id.tv_reserve_status);
                holder.cancelReserve = convertView.findViewById(R.id.btn_cancel_reserve);

                convertView.setTag(holder);
            } else
                holder = (CurrViewHolder) convertView.getTag();
            // update holder
            final Reservation r = reservationList.get(position);
            holder.time.setText(r.getStartTime() + "至" + r.getEndTime());
            holder.location.setText(r.getParkingName() + " " + r.getLotName());
            switch (r.getStatus()){
                case 0:
                    holder.status.setText("预约中");
                    holder.cancelReserve.setText("取消预约");
                    holder.cancelReserve.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cancelReserve(MainActivity.user.getReserveSysId(), r.getId());
                        }
                    });
                    break;
                case 1:
                    holder.status.setText("进行中");
                    holder.cancelReserve.setText("结束使用");
                    holder.cancelReserve.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finishReserve(MainActivity.user.getReserveSysId(), r.getLotId());
                        }
                    });
                    break;
            }

            // TODO 这里要不要对违规进行展示 ??
            return convertView;
        }
    }

    private static class HistoryViewHolder{
        TextView time, location, status, reason;
        LinearLayout operation;
    }

    private static class CurrViewHolder {
        TextView time, location, status;
        Button cancelReserve;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
